package com.atguigu.gulimall.order.listener;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.atguigu.gulimall.order.config.AlipayTemplate;
import com.atguigu.gulimall.order.service.OrderService;
import com.atguigu.gulimall.order.vo.PayAsyncVo;
import com.lly835.bestpay.service.impl.alipay.AliPaySignature;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@RestController
public class OrderPayedListener {

    @Resource
    OrderService orderService;

    @Resource
    AlipayTemplate alipayTemplate;

    @PostMapping("/payed/notify")
    public String handleAlipayed(PayAsyncVo vo, HttpServletRequest request) throws UnsupportedEncodingException, AlipayApiException {

        //验签
        HashMap<String, String> map = new HashMap<>();
        Map<String, String[]> parameterMap = request.getParameterMap();
        for(Iterator<String> iter = parameterMap.keySet().iterator();iter.hasNext();) {
            String name = iter.next();
            String[] values = parameterMap.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length-1)?valueStr+values[i]:valueStr+values[i]+",";
            }
//            valueStr = new String(valueStr.getBytes("ISO-8859-1"),"UTF-8");
            map.put(name,valueStr);
        }

        Boolean signVerified = AlipaySignature.rsaCheckV1(map,alipayTemplate.getAlipay_public_key(),alipayTemplate.getCharset(),alipayTemplate.getSign_type());
        if(signVerified){
            System.out.println("验签成功");
            String result = orderService.handlePayResult(vo);
            return result;
        }else {
            System.out.println("验签失败");
            return "error";
        }

    }
}
